package com.orange.common.ktx

import com.blankj.utilcode.util.LogUtils
import com.orange.common.util.MMKVUtils
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty

/**
 *  created by Orange on 2022/12/12 16:49
 *  参考
 *  mmkv 的 委托扩展
 *  https://juejin.cn/post/7043843490366619685
 */

fun mmkvInt(default: Int = 0) =
    MMKVProperty({ MMKVUtils.getInt(it, default) }, { MMKVUtils.put(first, second) })

fun mmkvLong(default: Long = 0L) =
    MMKVProperty({ MMKVUtils.getLong(it, default) }, { MMKVUtils.put(first, second) })

fun mmkvBool(default: Boolean = false) =
    MMKVProperty({ MMKVUtils.getBoolean(it, default) }, { MMKVUtils.put(first, second) })

fun mmkvFloat(default: Float = 0f) =
    MMKVProperty({ MMKVUtils.getFloat(it, default) }, { MMKVUtils.put(first, second) })

fun mmkvDouble(default: Double = 0.0) =
    MMKVProperty({ MMKVUtils.getDouble(it, default) }, { MMKVUtils.put(first, second) })

fun mmkvString(default: String = "") =
    MMKVProperty({ MMKVUtils.getString(it, default) }, {
        MMKVUtils.put(first, second)
    })

class MMKVProperty<V>(
    private val decode: (String) -> V,
    private val encode: Pair<String, V>.() -> Boolean
) : ReadWriteProperty<Any, V> {
    private var cache: V? = null

    override fun getValue(thisRef: Any, property: KProperty<*>): V {
        cache ?: decode(property.name).also { cache = it }
        LogUtils.d("读取mmkv ${property.name} = $cache")
        return cache!!
    }

    override fun setValue(thisRef: Any, property: KProperty<*>, value: V) {
        LogUtils.d("保存mmkv ${property.name} = $value")
        if (encode(property.name to value)) {
            cache = value
        }
    }
}